<?php

function db_connect( $host='localhost', $dbname, $user='root', $passwd='' ) {
	$connection = mysql_connect($host,$user,$passwd);
	if(!$connection){
		die("/*Database connection failed:" . mysql_error()."*/");
	}
	$db_select = mysql_select_db($dbname, $connection);
	if(!$db_select){
		die("/*Database selection failed: " . mysql_error()."*/");
	}
	mysql_set_charset('utf8',$connection); 
	return $connection;
}

function db_disconnect($connection){
	if(isset($connection)){
		mysql_close($connection);
	}
}

function do_query ($query) {
	$result = mysql_query($query);
	if (!$result) {
		fatal_error("/*A DB query error!<br>".mysql_error()."*/");
	} else {
		return($result);
	}
}


// responses
// ===============================================

function jsonId($id){
    $r = array(
        'success' => true,
        'id'	=> $id
    );
    return $r;
}

function jsonRecords($records){
    $r = array(
        'success' => true,
        'data'	=> $records
    );
    return $r;
}

function jsonResponse($success, $message = null, $title = null, $level = "INFO"){
    $rez = array(
        'success' => $success
    );
    if($message != null){
        $rez["message"] = $message;
        $rez["level"] = $level;
        if($title != null){
            $rez["title"] = $title;
        }
    }
    return $rez;
}

function jsonSuccess($message = null, $title = null, $level = "INFO"){
    return jsonResponse(true, $message, $title, $level);
}

function jsonError($message = null, $title = null, $level = "ERROR"){
    return jsonResponse(false, $message, $title, $level);
}

// renders
function renderSuccess($message = null, $title = null, $level = "INFO"){
	return json_encode(jsonSuccess($message, $title, $level));
}
function renderError($message = null, $title = null, $level = "ERROR"){
	return json_encode(jsonError($message, $title, $level));
}
function renderId($id){
	return json_encode(jsonId($id));
}
function renderRecords($records){
	return json_encode(jsonRecords($records));
}

function renderUnauthorized(){
    header('HTTP/1.1 401 Unauthorized');
    $rez = jsonError();
    $rez[UNAUTHORIZED_COD] = true;
    return json_encode($rez);
}

function renderExpectationFailed(){
    return renderError("Datele de intrare necorespunzatoare!", null, LEVEL_WARN); // TODO i18n
}


// end responses
// ===============================================


function fatal_error ($reason) {
    die($reason);
}

function sql2JSONObject($query) {
    $rezult = do_query($query);	
	$json = array();
    if($total = mysql_num_rows($rezult)) { //See if there is anything in the query
        while($data = mysql_fetch_assoc($rezult)) {
			$json[] = $data;
        }
    }
    return $json;
}

function sql2JSONArray($query) {
    $rezult = do_query($query);	
	$json = array();
    if($total = mysql_num_rows($rezult)) { //See if there is anything in the query
        while ($data = mysql_fetch_row($rezult)) {
			$json[] = $data;
		}
    }
    return $json;
}

function sql2HTMLTable($query){
	$result = do_query($query);	
	$table = '<table border="1">';
	// column headers
	$table = $table . '<tr>';
	$num = mysql_num_fields($result);
	for ($i = 0; $i < $num; ++$i) {
		$field = mysql_fetch_field($result, $i);
		$table = $table . '<th>' . $field->name . '</th>';
	}
	$table = $table . '</tr>';
	
	// column rows
    if($total = mysql_num_rows($result)) { //See if there is anything in the query
        while ($data = mysql_fetch_row($result)) {
			$table = $table . '<tr>';
			foreach($data as $v) {
				$table = $table . '<td>' . ($v != '' ? $v : '<span class="value-null">null</span>') . '</td>';
			}
			$table = $table . '</tr>';
		}
    }
	$table = $table . '</table>';
    return $table;
}

function onLogin($id, $email){
    $_SESSION['user_id'] = $id;
    $_SESSION['user_email'] = $email;
}

function resetActivationKey(){
    $userId = $_SESSION['user_id'];
    if($userId){
        $key = getNewKey($_SESSION['user_email']);
        $sql="UPDATE users SET activationkey = '$key' WHERE id = $userId";
        $r = do_query($sql);
    }
}

/**
 * @param  $emailTo
 * @param  $subject
 * @param  $body
 * @return array (JSON Array)
 */
function sentMail($emailTo, $subject, $body){
    echo '/*';

    require_once('conf/conf-mail.php');

    error_reporting(E_STRICT);
    //error_reporting(E_ALL);

    date_default_timezone_set('Europe/Bucharest');

    require_once('PHPMailer_v5.1/class.phpmailer.php');

    $mail = new PHPMailer();

    $mail->CharSet = 'utf-8';
    $mail->IsHTML(true);
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->SMTPDebug  = false;           // enables SMTP debug information (for testing)
                                         // 1 = errors and messages
                                         // 2 = messages only
    $mail->SMTPAuth   = true;            // enable SMTP authentication
    $mail->SMTPSecure = "ssl";           // sets the prefix to the servier
    $mail->Host       = MAIL_SMTP_HOST;  // sets GMAIL as the SMTP server
    $mail->Port       = MAIL_SMTP_PORT;  // set the SMTP port for the GMAIL server
    $mail->Username   = MAIL_SMTP_USER;  // GMAIL username
    $mail->Password   = MAIL_SMTP_PASS;  // GMAIL password

    $mail->SetFrom(MAIL_SMTP_FROM, MAIL_SMTP_NAME);
    $mail->AddReplyTo(MAIL_SMTP_FROM, MAIL_SMTP_NAME);
    $mail->Subject    = $subject;

    //$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
    $mail->MsgHTML($body);

    $mail->AddAddress($emailTo, "");

    //$mail->AddAttachment("images/phpmailer.gif");      // attachment

    if(!$mail->Send()) {
        echo '*/';
        return array (
            'success' => false,
            'message' => "Mailer Error: " . $mail->ErrorInfo
        );
    } else {
        echo '*/';
        return array (
            'success' => true,
            'message' => 'Message send!'
        );
    }
}

/**
 * @param  $email
 * @return string new activation key
 */
function getNewKey($email){
    return (time() . md5($email) . mt_rand() . mt_rand());
}


/**
 * // TODO verify
 * @param  $email
 * @return boolean
 */
function validateEmail($email){
    return (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email));
}


// ====================================================
// = = = = = = = = keywords = = = = = = = = = = = = = =
// ====================================================

function getKeywords(){
    require_once ("conf/conf.php");
    $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);

    $userId = $_SESSION['user_id'];
    // get keywords
    $sql = "SELECT id, keywords, style, cls, enabled FROM keywords WHERE user_id = $userId";
	$records = sql2JSONArray($sql);

    db_disconnect($connection);
	return renderRecords($records);
}
// ====================================================


// ====================================================
// = = = = = = = = = =  books = = = = = = = = = = = = =
// ====================================================

function getUserBookTheme($userId, $book, $chapter){
    $sql = "SELECT t.id, t.theme FROM user_chapters_theme as t JOIN chapter AS c ON (t.chapter_id = c.id) WHERE c.book_id = $book AND c.number = $chapter AND t.user_id = $userId";
    $result = do_query($sql);
    if(mysql_num_rows($result)) {
        if($data = mysql_fetch_row($result)) {
            return $data;
        }
    }
    return false;
}

// ====================================================

?>